package com.xrit.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xrit.constant.MessageConstant;
import com.xrit.result.Result;
import com.xrit.service.MemberService;
import com.xrit.service.ReportService;
import com.xrit.service.SetMealService;
import com.xrit.utils.DateUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("report")
public class ReportController {

    @Reference
    private MemberService memberService;

    @Reference
    private SetMealService setMealService;

    @Reference
    private ReportService reportService;

    /**
     * 导出运营统计数据报表
     */
    @RequestMapping("/exportBusinessReport")
    public void exportBusinessReport(HttpServletRequest req, HttpServletResponse res) throws Exception {
        // 获取运营统计数据
        Map<String, Object> reportData = reportService.getBusinessReportData();
        // 获取模板的路径, getRealPath("/") 相当于到webapp目录下
        String template = req.getSession().getServletContext().getRealPath("/template/report_template.xlsx");
        // 创建工作簿(模板路径)
        try (// 写在try()里的对象，必须实现closable接口，try()cathc()中的finally
             OutputStream os = res.getOutputStream();
             XSSFWorkbook wk = new XSSFWorkbook(template);){
            // 获取工作表
            XSSFSheet sht = wk.getSheetAt(0);

            // 日期 坐标 2,5
            sht.getRow(2).getCell(5).setCellValue(reportData.get("reportDate").toString());
            //======================== 会员 ===========================
            // 新增会员数 4,5
            sht.getRow(4).getCell(5).setCellValue(reportData.get("todayNewMember").toString());
            // 总会员数 4,7
            sht.getRow(4).getCell(7).setCellValue(reportData.get("totalMember").toString());
            // 本周新增会员数5,5
            sht.getRow(5).getCell(5).setCellValue(reportData.get("thisWeekNewMember").toString());
            // 本月新增会员数 5,7
            sht.getRow(5).getCell(7).setCellValue(reportData.get("thisMonthNewMember").toString());

            //=================== 预约 ============================
            sht.getRow(7).getCell(5).setCellValue(reportData.get("todayOrderNumber").toString());
            sht.getRow(7).getCell(7).setCellValue(reportData.get("todayVisitsNumber").toString());
            sht.getRow(8).getCell(5).setCellValue(reportData.get("thisWeekOrderNumber").toString());
            sht.getRow(8).getCell(7).setCellValue(reportData.get("thisWeekVisitsNumber").toString());
            sht.getRow(9).getCell(5).setCellValue(reportData.get("thisMonthOrderNumber").toString());
            sht.getRow(9).getCell(7).setCellValue(reportData.get("thisMonthVisitsNumber").toString());

            // 热门套餐
            List<Map<String,Object>> hotSetmeal = (List<Map<String,Object>> )reportData.get("hotSetmeal");
            int row = 12;
            for (Map<String, Object> setmealMap : hotSetmeal) {
                sht.getRow(row).getCell(4).setCellValue((String)setmealMap.get("name"));
                sht.getRow(row).getCell(5).setCellValue((Long)setmealMap.get("setmeal_count"));
                sht.getRow(row).getCell(6).setCellValue((String)setmealMap.get("proportion"));
                sht.getRow(row).getCell(7).setCellValue((String)setmealMap.get("remark"));
                row++;
            }
            String filename = "运营统计数据报表.xlsx";
            // 解决下载的文件名 中文乱码
            filename = new String(filename.getBytes(), "ISO-8859-1");
            // 设置头信息，告诉浏览器，是带附件的，文件下载
            res.setHeader("Content-Disposition","attachement;filename=" + filename);
            // 设置内容体的文件格式是excel
            res.setContentType("application/vnd.ms-excel");
            wk.write(os);
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取运营数据
     * @return
     */
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
        try{
            //使用模拟数据测试流程是否可以正常展示
            /**
             * reportData: {
             *  reportDate: null,//报表日期
             *  todayNewMember: 0,//新增会员数
             *  totalMember: 0,//总会员数
             *  thisWeekNewMember: 0,//本周新增会员
             *  thisMonthNewMember: 0,//本月新增会员
             *  todayOrderNumber: 0,//今日预约数
             *  todayVisitsNumber: 0,//今日到诊数
             *  thisWeekOrderNumber: 0,//本周预约数
             *  thisWeekVisitsNumber: 0,//本周到诊数
             *  thisMonthOrderNumber: 0,//本月预约数
             *  thisMonthVisitsNumber: 0,//本月到诊数
             *  hotSetmeal: []
             * }
             */
            /*Map<String,Object> map=new HashMap<>();
            map.put("reportDate","2021-12-12");
            map.put("todayNewMember",10);
            map.put("totalMember",100);
            map.put("thisWeekNewMember",200);
            map.put("thisMonthNewMember",1000);
            map.put("todayOrderNumber",20);
            map.put("todayVisitsNumber",100);
            map.put("thisWeekOrderNumber",400);
            map.put("thisWeekVisitsNumber",2000);
            map.put("thisMonthOrderNumber",800);
            map.put("thisMonthVisitsNumber",5000);

            List<Map<String,Object>> list=new ArrayList<>();
            Map<String,Object> map1=new HashMap<>();
            map1.put("name","阳光爸妈升级肿瘤12项筛查（男女单人）体检套餐");
            map1.put("setmeal_count",200);
            map1.put("proportion",0.222);
            list.add(map1);
            Map<String,Object> map2=new HashMap<>();
            map2.put("name","阳光爸妈升级肿瘤12项筛查体检套餐");
            map2.put("setmeal_count",100);
            map2.put("proportion",0.222);
            list.add(map2);
            map.put("hotSetmeal",list);
*/
            Map<String, Object> map = reportService.getBusinessReportData();
            return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,map);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new Result(true,MessageConstant.GET_BUSINESS_REPORT_FAIL);
    }

    /**
     * 套餐统计
     * @return
     */
    @RequestMapping("/getSetmealReport.do")
    public Result getSetmealReport(){
        List<Map<String, Object>> map = setMealService.findSetmealCount();
        return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,map);
    }

    @RequestMapping("/getMemberReport.do")
    public Result getMemberReport(){
        Map map=new HashMap();
//        map.put("months",new String []{"2021-10","2021-11","2021-12","2022-01",});
//        map.put("memberCount",new Integer[]{100,200,300,400});
        //1.过去一年的时间
        List<String> months = DateUtils.getLastYear4Month("YYYY.MM");
        map.put("months",months);
        //2.过去一年中每个月的最后一天所累计的总会员数
        List<Integer> memberCount = memberService.getMemberReport(months);
        map.put("memberCount",memberCount);
        return new Result(true, MessageConstant.QUERY_CHECKGROUP_FAIL,map);
    }
}
